package com.example.springstudy.controller;

import com.example.springstudy.common.SuccessResult;
import com.example.springstudy.entity.ChartVal;
import com.example.springstudy.services.ChartValRepository;
import lombok.Data;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

// 数据报警控制器
@RestController
@RequestMapping("api/chart")
public class ChartController {
    @Resource
    private ChartValRepository chartValRepository;


    // 根据条件获取一个小时内的数据
    @PostMapping("hour")
    public SuccessResult<List<ChartVal>> getHourList(@RequestBody HourListParam param) {
        // 当前时间
        String endTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        // 一个小时之前的时间
        String startTime = LocalDateTime.now().plusHours(-1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Specification<ChartVal> specification = (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> listAnd = new ArrayList<>(); //组装and语句
            // 过滤 测量类型
            listAnd.add(criteriaBuilder.equal(root.get("measuringType"), param.getMeasuringType()));

            //起始日期
            if (!startTime.trim().equals("")) {
                listAnd.add(criteriaBuilder.greaterThanOrEqualTo(root.get("createTime").as(String.class), startTime));
            }
            //结束日期
            if (!endTime.trim().equals("")) {
                listAnd.add(criteriaBuilder.lessThanOrEqualTo(root.get("createTime").as(String.class), endTime));
            }

            Predicate predicateAnd = criteriaBuilder.and(listAnd.toArray(new Predicate[listAnd.size()])); //AND查询加入查询条件

            List<Predicate> listOr = new ArrayList<>();///组装or语句
            if (param.getCodes().size() > 0) {
                for (String code : param.getCodes()) {
                    // 多个code 用 or 连接
                    listOr.add(criteriaBuilder.equal(root.get("deviceCode"), code));
                }
            }
            Predicate predicateOR = criteriaBuilder.or(listOr.toArray(new Predicate[listOr.size()])); //OR查询加入查询条件
            return criteriaQuery.where(predicateAnd, predicateOR).getRestriction();
        };
        List<ChartVal> all = chartValRepository.findAll(specification);

        return new SuccessResult<>(all);
    }
}

@Data
class HourListParam {
    // 设备code 列表
    private List<String> codes;

    // 测量类型(湿度 温度  X Y)
    private String measuringType;

}
